package cn.funnymap.lgis.mp.operator;

import cn.funnymap.lgis.mp.entity.BaseCatalogNodeEntity;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jiaoxn
 */
@Slf4j
public class CatalogUtil {
    private CatalogUtil() {}

    // region 目录树实体转VO
    public static <T extends BaseCatalogNodeEntity, V extends CatalogNodeVO> V asTree(
            List<T> entityList, CatalogEntityConverter<T, V> converter) {
        return asTree(entityList, converter, false);
    }
    public static <T extends BaseCatalogNodeEntity, V extends CatalogNodeVO> V asTree(
            List<T> entityList, CatalogEntityConverter<T, V> converter, boolean firstIsRoot) {
        // 将Entity List转为VO Map（LinkedHashMap，保证插入顺序），path作为key、对应的VO实例作为值
        Map<String, V> voMap = entityList.stream()
                .collect(Collectors.toMap(
                        BaseCatalogNodeEntity::getPath,
                        converter::execute,
                        (a, b) -> a,
                        LinkedHashMap::new));
        return flatVoMap(entityList, voMap, firstIsRoot);
    }
    private static <T extends BaseCatalogNodeEntity, V extends CatalogNodeVO> V flatVoMap(
            List<T> entityList, Map<String, V> voMap, boolean firstIsRoot) {
        V vo = null;

        if (firstIsRoot) {
            vo = voMap.get(entityList.get(0).getPath());
        }

        for (BaseCatalogNodeEntity entity : entityList) {
            String path = entity.getPath();

            if ("root".equals(entity.getLevel()) && !firstIsRoot) {
                vo = voMap.get(path);
            } else {
                String parentNodePath = path.substring(0, path.lastIndexOf("."));
                V parentNodeVo = voMap.get(parentNodePath);

                if (parentNodeVo != null) {
                    parentNodeVo.getChildren().add(voMap.get(path));
                }
            }
        }

        return vo;
    }
    // endregion

    public static String getParentNodePath(String path) {
        String[] pathItems = path.split("\\.");

        if (pathItems.length >= 2) {
            return pathItems[pathItems.length - 2];
        }

        return null;
    }
}
